package com.audaque.springboot.foshanupload.gateway.filter;

/**
 * @author zgb
 * @desc ...
 * @date 2023-08-01 17:25:24
 */


import com.audaque.springboot.foshanupload.cloudcore.constants.CloudConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器
 */
@Slf4j
@Component
public class FromGatewayFilter implements GlobalFilter, Ordered {



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("执行前置过滤器逻辑");
        //ASCII编码
        //可逆
        //没有秘钥，不安全
        byte[] b = Base64Utils.encode((CloudConst.FROM_GATEWAY_HEADER_KEY).getBytes());
        //静态初始化
        String[] headerValues = {new String(b)};
        ServerHttpRequest build = exchange.getRequest()
                .mutate()
                //设置header
                .header(CloudConst.FROM_GATEWAY_HEADER_KEY, headerValues)
                .build();
        //更新header
        ServerWebExchange newExchange = exchange.mutate().request(build).build();
        return chain.filter(newExchange).then(Mono.fromRunnable(()->{
            log.debug("执行后置过滤器逻辑");
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
